package com.powernode.controller;

import com.powernode.common.Constants;
import com.powernode.common.Result;
import com.powernode.domain.User;
import com.powernode.service.UserService;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;

/**
 * 描述：完成用户的登陆和退出
 */
@RestController
@RequestMapping("login")
public class LoginController {

    @Resource
    private UserService userService;

    /**
     * 登陆方法
     */
    @PostMapping  ("login.action")
    public Result login(String username, String password, String captcha,HttpSession session){
        //得到正确的验证码、
        String trueCode = session.getAttribute(Constants.CAPTCHA_CODE_KEY).toString();
        //判断用户输入的验证码和正确的验证是否一样
        if(trueCode.equalsIgnoreCase(captcha)){
            User user=this.userService.login(username, DigestUtils.md5DigestAsHex(password.getBytes()) );
            if(null==user){
                return new Result(-1,"用户名或密码不正确");
            }
            //把用户放到session
            user.setPassword("");
            session.setAttribute(Constants.SESSION_USER_KEY,user);
            return new Result(200,"登陆成功");
        }else{
            return new Result(-1,"验证码不正确");
        }
    }

    /**
     * 退出登陆
     */
    @PostMapping("loginOut.action")
    public Result loginOut(HttpSession session){
        try {
            session.invalidate();
            return new Result(200,"退出成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(-1,"退出失败");
        }
    }


}